package com.hxzy.service.impl;

import com.hxzy.common.constants.MarketConstants;
import com.hxzy.common.constants.RedisConstants;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.controller.admin.login.req.AdminLoginReq;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.service.AdminLoginService;
import com.hxzy.service.EmployeeService;
import com.hxzy.service.MerchandiserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 后台登录业务逻辑
 */
@Service
public class AdminLoginServiceImpl implements AdminLoginService {

    @Autowired
    private RedisTemplate  redisTemplate;

    /**
     * 管理员业务逻辑
     */
    @Autowired
    private EmployeeService  employeeService;

    /**
     * 商家业务逻辑
     */
    @Autowired
    private MerchandiserService  merchandiserService;

    @Transactional
    @Override
    public AdminLoginResp login(AdminLoginReq req) {
        //验证码
        String redisKey= RedisConstants.CAPTCHA_PREFIX + req.getUuid();
        Object redisValue = this.redisTemplate.opsForValue().get(redisKey);
        //验证码不存在
        if(Objects.isNull(redisValue)){
            throw new ServiceException(AckCode.CODE_NOT_FOUND);
        }

        //删除验证码
        this.redisTemplate.delete(redisKey);

        //验证码不相同
        if(!redisValue.toString().equalsIgnoreCase(req.getCode())){
            throw new ServiceException(AckCode.CODE_ERROR);
        }

        //判断到底执行哪一个登录操作
        //工厂方法代码
        AdminLoginService  loginService=null;
        if(MarketConstants.ACCOUNT_ADMIN_TYPE.equals( req.getAccountType())){
            loginService=this.employeeService;

        }else if(MarketConstants.ACCOUNT_MERCHANDISER_TYPE.equals(req.getAccountType())){
            loginService=this.merchandiserService;
        }else{
            throw new ServiceException(AckCode.ACCOUNT_TYPE_ERROR);
        }

        //登录操作

        AdminLoginResp adminLoginResp = loginService.login(req);
        return adminLoginResp;
    }



}
